<?php
namespace addons\TfFutures\api\controllers;

use addons\TfFutures\common\models\SymbolCate;
use common\helpers\ResultDataHelper;
use Yii;
use api\controllers\OnAuthController;
use addons\TfFutures\common\models\Symbol;
use addons\TfFutures\common\models\SymbolToa;
use addons\TfFutures\common\models\Member;
use addons\TfFutures\common\models\MemberLever;
use addons\TfFutures\common\models\Setup;
use addons\TfFutures\common\models\Order;
use addons\TfFutures\services\OrderService;
use trade\common\service\KlineService;
use addons\TfFutures\common\models\Logs;

class SymbolController extends OnAuthController
{
    public $modelClass = Symbol::class;

    /**
     * 不用进行登录验证的方法
     * 例如： ['index', 'update', 'create', 'view', 'delete']
     * 默认全部需要验证
     *
     * @var array
     */
    protected $optional = ['recommend','get-one','sym-list','index','cate-lists','get-cate','get-symbols','getlist-by-id','aa','overfee','catelist-by-id','cate-list'];

    /**
    *产品列表
    */
    public function actionIndex()
    {
        if (!Yii::$app->request->isGet){
            return ResultDataHelper::api('403', 'Access done!');
        }
        
        $results = Symbol::find()->where(['status'=>1])->orderBy('sort,id asc')->asArray()->all();
        foreach ($results as $k => $v){

//            if(in_array($v['id'],$a)){
//
//                $results[$k]['optional'] = 1;
//            }else{
                $results[$k]['optional'] = '';
//            }
        }
        return ResultDataHelper::api(200, 'ok',$results);
    }
    /*
     * 产品分类列表
     * */
    public function actionCateList(){
        if (!Yii::$app->request->isGet){
            return ResultDataHelper::api('403', 'Access done!');
        }
        //获取产品列表
        $model = SymbolCate::find()->where(['status'=>1])->asArray()->all();
        foreach ($model as $k=>$v) {
            $model[$k]['symbols'] = Symbol::find()->where(['cate_id'=>$v['id'],'on_sale'=>'on'])->asArray()->all();
            $uid = Yii::$app->user->identity->member_id;
            if(!empty($uid)){
            	$data = Member::find()->where(['member_id'=>$uid])->asArray()->one();
    			$a = explode(',',$data['symbol']);
    			foreach ($model[$k]['symbols'] as $key => $val){
            		if(in_array($val['id'],$a)){
                		$model[$k]['symbols'][$key]['zixuan'] = 1;
            		}else{
                		$model[$k]['symbols'][$key]['zixuan'] = 0;
            		}
        		}
            }
        }
        return ResultDataHelper::api(200, 'ok',$model);
    }

    /*
     * 根据父级分类获取产品分类列表及产品
     * */
    public function actionCatelistById($id){
        if (!Yii::$app->request->isGet){
            return ResultDataHelper::api('403', 'Access done!');
        }
        //获取产品列表
        $model = SymbolCate::find()->where(['status'=>1,'pid'=>$id])->asArray()->all();
        foreach ($model as $k=>$v) {
            $model[$k]['symbols'] = Symbol::find()->where(['cate_id'=>$v['id']])->all();
        }
        return ResultDataHelper::api(200, 'ok',$model);
    }

    /*
     * 产品分类列表(获取一个数组的)
     * */
    public function actionCateLists(){
        if (!Yii::$app->request->isGet){
            return ResultDataHelper::api('403', 'Access done!');
        }
        //先获取顶级分类的列表
        $topCate = SymbolCate::find()->where(['level'=>1,'status'=>1])->asArray()->all();

        if (empty($topCate)){
            return ResultDataHelper::api(422, '未查询到产品分类');
        }
        foreach ($topCate as $k=>$item) {
            $childCate = SymbolCate::find()->where(['pid'=>$item['id'],'status'=>1])->asArray()->all();
            $topCate[$k]['childCate'] = $childCate;
            //获取子分类下的所有产品
            foreach ($childCate as $k1=>$item1) {
                $topCate[$k]['childCate'][$k1]['symbols'] = Symbol::find()->where(['cate_id'=>$item1['id'],'status'=>1])->asArray()->all();

                //$symbols;
            }
        }
        return ResultDataHelper::api(200, 'ok',$topCate);
    }


    //获取指定分类的子分类,id=0 获取顶级分类
    public function actionGetCate($id){
        if (!Yii::$app->request->isGet){
            return ResultDataHelper::api('403', 'Access done!');
        }
        $childCate = SymbolCate::find()->where(['pid'=>$id,'status'=>1])->asArray()->all();
        return ResultDataHelper::api(200, 'ok',$childCate);
    }

    //获取指定分类下的产品
    public function actionGetSymbols($id){
        if (!Yii::$app->request->isGet){
            return ResultDataHelper::api('403', 'Access done!');
        }
        $symbols = Symbol::find()->where(['cate_id'=>$id])->all();
        return ResultDataHelper::api(200, 'ok',$symbols);
    }







    /*
     * 产品搜索
     * 
    public function actionSearchSymbol(){
        if (!Yii::$app->request->isGet){
            return ResultDataHelper::api('403', 'Access done!');
        }
        $keyword = Yii::$app->request->get('keyword');

        if (empty($keyword)) {
            $where = ['>','id',0];
        }else{
            $where = ['like', 'name', $keyword];
        }
        $model = Symbol::find()->where($where)->limit(5)->all();
        return ResultDataHelper::api(200, 'ok',$model);
    }*/
    
    /*
     * 产品搜索
     * */
    public function actionSearchSymbol(){
        if (!Yii::$app->request->isGet){
            return ResultDataHelper::api('403', 'Access done!');
        }
        $code = Yii::$app->request->get('code');
        if ($code){
            $model = Symbol::find()->where(['or',['like','code',$code],['like','name',$code]])
                ->andFilterWhere(['status'=>1])
                ->asArray()->limit(5)->all();
            $uid = Yii::$app->user->identity->member_id; 
            $data = Member::find()->where(['member_id'=>$uid])->asArray()->one();
            $a = explode(',',$data['symbol']);
            foreach ($model as $key => $val){
                if(in_array($val['id'],$a)){
                    $model[$key]['zixuan'] = 1;
                }else{
                    $model[$key]['zixuan'] = 0;
                }
            }
        }
        return ResultDataHelper::api(200, 'ok',$model);
    }


    /**
     * 产品涨幅榜单 (未完工)
     * @return mixed
     */
    public function actionList()
    {
        if (!Yii::$app->request->isPost) {
            return ResultDataHelper::api('403', 'Access done!');
        }
        $id = Yii::$app->request->post('id');
        //获取产品列表
        $model = Symbol::findOne($id);
        return ResultDataHelper::api('200', '成功', $model);
    }
    /*
     * 获取产品信息
     * */
    public function actionGetOne(){
        if (!Yii::$app->request->isGet){
            return ResultDataHelper::api('403', 'Access done!');
        }
        $id = Yii::$app->request->get('code');
        if (empty($id)) {
            return ResultDataHelper::api('422', '产品code不能为空');
        }
        //$model = Symbol::findOne($id);
        $model = Symbol::find()->where(['code'=>$id])->one();
        return ResultDataHelper::api('200', 'ok', $model);
    }
    /*
     * 获取推荐产品
     *
     * */
    public function actionRecommend(){
        if (!Yii::$app->request->isGet){
            return ResultDataHelper::api('403', 'Access done!');
        }
        $model = Symbol::find()
            ->where(['recommend'=>'1'])
            ->all();
        return ResultDataHelper::api('200', 'ok', $model);
    }
    /*
     * 行情列表
     * */
    public function actionSymList(){
        if (!Yii::$app->request->isGet){
            return ResultDataHelper::api('403', 'Access done!');
        }
        $model = Symbol::find()->asArray()->all();
        foreach($model as $k=>$v){
            //获取最新价格
            Yii::$app->services->kline->prex = 'rf_addon_tf_futures_symbol';

            $newPrice = Yii::$app->services->kline->loadTicekt($v['code']);
            $model[$k]['newprice'] = $newPrice;
        }
        return ResultDataHelper::api('200', 'ok', $model);
    }
    /*
     * 分类下行情列表
     * */
    public function actionSymLists(){
        if (!Yii::$app->request->isGet){
            return ResultDataHelper::api('403', 'Access done!');
        }
        $cateid = Yii::$app->request->get('cateid');
        $model = Symbol::find()->where(['cate_id' => $cateid])->asArray()->all();
        $uid = Yii::$app->user->identity->member_id; 
        $data = Member::find()->where(['member_id'=>$uid])->asArray()->one();
        $a = explode(',',$data['symbol']);
        foreach ($model as $key => $val){
            if(in_array($val['id'],$a)){
                $model[$key]['optional'] = 1;
            }else{
                $model[$key]['optional'] = 0;
            }
        }
        foreach($model as $k=>$v){
            //获取最新价格
            Yii::$app->services->kline->prex = 'rf_addon_tf_futures_symbol';

            $newPrice = Yii::$app->services->kline->loadTicekt($v['code']);
            $model[$k]['newprice'] = $newPrice;
        }
        return ResultDataHelper::api('200', 'ok', $model);
    }
    
     /**
	* 自选分类列表
	*/
	public function actionCate()
	{
		 if (!Yii::$app->request->isGet) {
		     return ResultDataHelper::api(304, 'access done!');
		 }
		 $uid = Yii::$app->user->identity->member_id;
		 if (empty($uid)) {
	        return ResultDataHelper::api(422, '用户id不能为空');
	    }
	    list($memberc, $member) = Member::member($uid);
	    if (empty($memberc)) {
	        return ResultDataHelper::api(422, '用户不存在');
	    }
	    $array = [];
	    $models = SymbolCate::find()->where(['status'=>1])->asArray()->all();
	    foreach ($models as $key => $val){
	    	$array[] = $val['id'];
	    }
	    $arr   = explode(',', $member->cate);
	   
	    $modela = SymbolCate::find()->where(['in','id',$arr])->asArray()->all();
	    foreach($modela as $key=>$val){
	    	if (!empty($val)) {
	    		$modela[$key]['opp'] = 1;
	    	}
	   	}
	    $newarr = array_diff($array,$arr);
	    $modelb = SymbolCate::find()->where(['in','id',$newarr])->asArray()->all();
	    foreach($modelb as $key=>$val){
	    	if (!empty($val)) {
	    		$modelb[$key]['opp'] = 0;
	    	}
	   	}
	    $model['new'] = $modela;
	    $model['old'] = $modelb;
	    return ResultDataHelper::api(200,'ok',$model);
	 }
	 
	 /**
     * 删除自选分类
     */
    public function actionDelCate(){
        if (!Yii::$app->request->isPost) {
            return ResultDataHelper::api(304,'access done!');
        }
        $uid = Yii::$app->user->identity->member_id;
        if (empty($uid)) {
            return ResultDataHelper::api(422,'用户id不能为空');
        }
        $member = Member::find()->where(['member_id'=>$uid])->one();
        $id = Yii::$app->request->post('cate_id');
        if (empty($id)) {
            return ResultDataHelper::api(422,'产品分类id不能为空');
        }
        $arr = explode(',',$member->cate);
        $ids[] = $id;
        //$delarr = explode(',',$ids);
        //$delarr = explode(',',$id);
        $newarr = array_diff($arr,$ids);
        $member->cate = implode(',',$newarr);
        if (!$member->save()) {
            return ResultDataHelper::api(422, $this->analyErr($member->getFirstErrors()));
        }
        return ResultDataHelper::api(200,'删除成功');
    }
    
    /**
     * 添加自选分类
     */
    public function actionAddCate(){
        if (!Yii::$app->request->isPost) {
            return ResultDataHelper::api(304,'access done!');
        }
        $uid = Yii::$app->user->identity->member_id;
        if (empty($uid)) {
            return ResultDataHelper::api(422,'用户id不能为空');
        }
        list($memberc,$member) = Member::member($uid);
        if (empty($memberc)) {
            return ResultDataHelper::api(422,'用户不存在');
        }
        $id = Yii::$app->request->post('cate_id');
        if (empty($id)) {
            return ResultDataHelper::api(422,'添加的产品分类id不能为空');
        }
        $symbol = SymbolCate::findOne($id);
        if(empty($symbol)){
        	return ResultDataHelper::api(422,'分类不存在');
        }
        $symbolarr = explode(',',$member->cate);
        if(in_array($id,$symbolarr)){
            return ResultDataHelper::api(422,'您已经添加过该分类');
        }
        $idarr = explode(',',$id);
        $newarr = array_unique(array_merge($symbolarr,$idarr));
        
          
        if($newarr[0]==null){
          	unset($newarr[0]);
        }
          //print_r($newarr);die;
        $member->cate = implode(',',$newarr);
        if (!$member->save()) {
            return ResultDataHelper::api(422, $this->analyErr($member->getFirstErrors()));
        }
        return ResultDataHelper::api(200,'添加成功');
    }

	/**
     * 更新排序
     * @return mixed
     */
    public function actionUpdateSort()
    {
        if (!Yii::$app->request->isPost) {
            return ResultDataHelper::api(403, 'Access Done');
        }
        $uid    = Yii::$app->user->identity->member_id;
        $member = Member::find()->where(['member_id'=>$uid])->one();
        if (empty($member)) {
            return ResultDataHelper::api(422, '用户不存在');
        }
        $member_arr = explode(',', $member->cate);
        if (empty($member_arr)) {
            return ResultDataHelper::api(422, '请先添加自选产品');
        }
        $sort     = Yii::$app->request->post('sort');
        $sort_arr = explode(',', $sort);
        if (empty($sort_arr)) {
            return ResultDataHelper::api(422, '没有排序数据');
        }
        $s1 = sort($member_arr);
        $s2 = sort($sort_arr);
        // print_r($member_arr);die;
        if ($member_arr != $sort_arr) {
            return ResultDataHelper::api(422, '数据错误无法进行排序');
        }
        $member->cate = $sort;

        if (!$member->save()) {
            return ResultDataHelper::api(422, '更新排序失败');
        }
        return ResultDataHelper::api(200, '更新排序成功');
    }
    //爆仓比测试
    public function actionAa()
    {
    	//用户资产查询
    	$member_price = Member::find();
        $members = $member_price->all();
        //爆仓比列
        $setup  = Setup::findOne(1);
        //个人持仓订单
         
        foreach($members as $member)
        {
			//个人持仓订单
            $all_profit = Order::find()
                ->where(['state' => '持仓', 'member_id' => $member->member_id])
                ->select("sum(`profit`) as all_profit,lever_id,member_id")
                ->orderBy('lever_id desc')
                ->asArray()
                ->all();
            if(empty($all_profit) ){
            	continue;
            }
            foreach ($all_profit as $k =>$v)
            {
            	
            	
            	
                $prcie = $member_price->where(['member_id'=>$v['member_id']])->asArray()->one();
                
                // 计算爆仓比
                $percentage = bcmul($prcie['price'], bcdiv($setup['close'], 100, 4), 4);
                
                if($v['all_profit']>0){
                	continue;
                }
                if (abs($v['all_profit']) > $percentage) {
                    //先查询所有订单
                    $order = Order::find()
                        ->where([
                            'member_id' => $v['member_id'],
                            'state'	  =>'持仓'
                        ])
                        ->all();
						// print_r($v);
                    //循环平仓
                    foreach ($order as $key => $val) {
                        OrderService::OrderClose($val->id, NULL, '强制平仓');
                    }
                    $lever = memberlever::find()->where(['id' => $v['lever_id'],'state'=>'正常'])->one();
                    if(!empty($lever)){
                    	$lever->state = '禁用';
                    	$lever->save();
                    }
                    
                }
            }
        }
    }
    public function actionOverfee(){
     //过夜费overtime
        $symbols = Symbol::find()->where(['status'=>'1','on_sale'=>'on'])->all();
        foreach( $symbols as $symbol =>$v ){
	        $orders = Order::find()->where(['symbol'=>$v['code'],'state'=>'持仓','status'=>'1'])->all();
	        // print_r($orders);
	        foreach( $orders as $order =>$val ){
				$order = Order::find()->where(['id'=>$val->id])->one();
				$member_price= Member::find()->where(['member_id'=>$val->member_id])->one();
                $data = date('Y-m-d H:i:s');
                $order->overfee = $order->overfee+($order['deposit']*$v->overfee/10000);
                $order->overtime = $data;
                $member_price->price = $member_price->price-($order['deposit']*$v->overfee/10000);
                if($member_price->price < ($order['deposit']*$v->overfee/10000)){
                	$orderlist = Order::find()->where(['member_id'=>$member_price->member_id,'state'=>'持仓'])->all();
                	// print_r($orderlist);die;
                	foreach ($orderlist as $key =>$value){
                		// print_r($value->id);die;
                		OrderService::OrderClose($value->id,'NULL','强制平仓');
                		// echo '1*2';
                	}
                }
                $order->save();
                $member_price->save();
                Logs::addLogs($val->member_id, '过夜费', $order['deposit']*$v->overfee/10000, bcadd($member_price->price, $order['deposit']*$v->overfee/10000, 4), $member_price->price, '用户扣除过夜费');
	        }
            
        }
    }
}